---@class Battle.AiPathFindingAction:Battle.AiLeaf
---@field New fun():Battle.AiPathFindingAction
local AiPathFindingAction = Battle.CreateClass("AiPathFindingAction",Battle.AiLeaf)
Battle.AiPathFindingAction = AiPathFindingAction
local t = AiPathFindingAction

function t:Awake()
    self:SetParamKey(1,"isFixPos")
    self:SetParamKey(2,"target")--目标actor or pos
    self.targetPos = Vector3.New()
    self.startPos = Vector3.New()
    self.endPos = Vector3.New()
    self.pos = Vector3.New()
    self.UpdateTargetPosDis = 0.1
end
function t:onInitialize()
    ---@type Battle.Entity
    self.actor = self:GetActor()
    self:UpdateParam()
    self:InitMove()
end
function t:onTerminate()
    self.actor.eventSystem:FireEvent(Battle.Event.StopPathFind)
    self.actor:EnterState(Battle.ActionState.idle)
end
function t:update(dt)
    if not self.actor.effectStateSystem:CanMove() then
        return Battle.AiTreeStatus.FAILURE
    end
    if not self.isFixPos then
        if self.target == nil then
            return Battle.AiTreeStatus.FAILURE
        end
        if self.target:IsDead() then
            self.actor:EnterState(Battle.ActionState.idle)
            return Battle.AiTreeStatus.SUCCESS
        end
    end
    if self:IsTargetMove() then
        self:InitMove()
    end
    self.actor:EnterState(Battle.ActionState.run)
    if not self.actor:IsMoving() then
        return Battle.AiTreeStatus.SUCCESS
    end

    return Battle.AiTreeStatus.RUNNING

end
function t:InitMove()
    self.endPos:SetV(self.targetPos)
    self.actor.eventSystem:FireEvent(Battle.Event.StartPathFind,Battle.EventArgs.StartPathFindArgs:Create(self.endPos))
end
function t:IsTargetMove()
    self:UpdateParam()
    if (Vector3.DistanceSqr(self.endPos,self.targetPos) > self.UpdateTargetPosDis*self.UpdateTargetPosDis) then
        return true
    end
    return false
end
function t:UpdateParam()
    self.isFixPos = self:GetParam("isFixPos")
    if self.isFixPos then
        local p = self:GetParam("target")
        self.targetPos:SetV(p)
    else
        self.target = self:GetParam("target")
        if not self.target then
            return
        end
        self.targetPos:SetV(self.target:GetPos())
    end
end